package com.lzb.newloan;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.veltical.text.TimeTaskScroll;
import com.lzb.newloan.adapter.HomeAdapter;
import com.lzb.newloan.bqs.CatLoadingView;
import com.lzb.newloan.menu.ResideMenu;
import com.lzb.newloan.pojo.PersonPojo;
import com.lzb.newloan.utils.AlertDialog;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.Formatdou;
import com.lzb.newloan.utils.HttpUtils;
import com.lzb.newloan.utils.StreamUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;

public class HomeFragment extends Fragment {
	private View view;
	private int rzstatus,sfzmrz;
	private int isshenfen;
	private int isjob;
	private int islianxi, ismobile, istaobao, isjd;
	private Activity ac;
	private TextView get_money;
//	private VerticalScrollTextView record_list;
	private ListView record_list;
	private ArrayList<PersonPojo> arrPojos;
	private HomeAdapter adapter;
	private String mobilephone, cardBank;
	private String jkid;
	private TextView out_money_txt;
	private int wdXiaoXi = 0,isApplerz;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.fragment_home2, container, false);
			initView();
			initData();
		} else {
			((ViewGroup) view.getParent()).removeView(view);
		}
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
//		if (time==null) {
//			time = new Timer();
//		}
		super.onStart();
	}
	
	private void initView() {
		ac = getActivity();
		dialog = new CatLoadingView(ac);
		dialog.show();
		TextView title_txt_center = (TextView) view
				.findViewById(R.id.title_txt_center);
		title_txt_center.setText("钱宝包");
		view.findViewById(R.id.title_irrow).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ResideMenu menu = ((IndexActivity) ac).getResideMenu();
				menu.openMenu(ResideMenu.DIRECTION_LEFT);
			}
		});
		
		news_warm = (ImageView) view.findViewById(R.id.news_warm);
		time = new Timer();
		txt = (TextView) view.findViewById(R.id.txt);
		view.findViewById(R.id.title_right_rela).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ac, NewsActivity.class);
						startActivity(intent);
					}
				});
//		view.findViewById(R.id.problem).setOnClickListener(
//				new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						Intent intent = new Intent(ac, ProblemActivity.class);
//						intent.putExtra("title", "常见问题");
//						intent.putExtra("url", "http://www.lvzbao.com/androidHtml/sdxcjwt_app.html");
//						startActivity(intent);
//					}
//				});
		get_money = (TextView) view.findViewById(R.id.get_money);
		out_money_txt = (TextView) view.findViewById(R.id.out_money_txt);
		out_money_txt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ConnectionDetector cd = new ConnectionDetector(ac);
				if (cd.isConnectingToInternet()) {
					String type = out_money_txt.getText().toString();
//					if (isApplerz==0) {// 请绑定银行卡
//						setDialog("bank", "请先绑定银行卡！");
////						HttpUtils.doGetAsyn(Config.HOME_INIT + "&userid="
////								+ userId, mHandler, Config.CODE_BANK);
//						return;
//					}
					switch (type) {
					case "借款":
                        if (isApplerz==1){
						setDialog("bank", "银行卡正在认证,请先填基本资料！");
						return;
					    }
                        if (isApplerz==0){
                            setDialog("bank", "请先绑定银行卡！");
                            return;
                        }
						if (isshenfen != 1) {// 请填写个人信息
							setDialog("bank", "请先绑定个人资料！");
							return;
						}
						if (isjob != 1) {// 请填写工作信息
							setDialog("bank", "请先绑定工作信息！");
							return;
						}
						if (islianxi != 1) {// 请填写联系人信息
							setDialog("bank", "请先绑定联系人！");
							return;
						}
						if (ismobile != 1) {
							setDialog("bank", "请先进行授权！");
							return;
						}
						if (isjd != 1) {
							if (istaobao != 1) {
								setDialog("bank", "请先进行授权！");
								return;
							}
						}
						if (istaobao != 1) {
							if (isjd != 1) {
								setDialog("bank", "请先进行授权！");
								return;
							}
						}
						if (sfzmrz!=1) {
							setDialog("bank", "请先进行芝麻认证！");
							return;	
						}

						Intent intent = new Intent(ac, IWantMoneyActivity.class);
						intent.putExtra("phone", mobilephone);
						intent.putExtra("cardBank", cardBank);
						startActivity(intent);
						break;
					case "查看借款详情":
						Intent intentc = new Intent(ac,
								OutMoneyRecordActivity.class);
						intentc.putExtra("type", "home");
						startActivity(intentc);

						break;
					case "上传视频":
						if (ismobile != 1) {
							setDialog("bank", "运营商授权已失效请重新授权");
							return;
						}
						Intent intentv = new Intent(ac, CameraActivity.class);
						intentv.putExtra("jkid", jkid);
						startActivity(intentv);
						// setDialog("camera",
						// "录制视频时请使用前置摄像头对着本人并说'我叫***,从钱宝包贷借款**元'！");
						break;
					case "还款":
						HttpUtils.doPostAsyn(Config.CHECKBACKMONEY_CORD + "&userid=" + userId+"&jkid="+jkid, "",mHandler,
								Config.CODE_CHECKBACKMONEY);
						break;
					case "等待放款中":
						Intent intento = new Intent(ac,
								OutMoneyRecordActivity.class);
						intento.putExtra("type", "home");
						startActivity(intento);
						break;
					default:
						break;
					}
				}

			}
		});
		record_list = (ListView) view.findViewById(R.id.record_list);

	};

	private void initData() {
		SharedPreferences sp = ac.getSharedPreferences("config", 0x0000);
		userId = sp.getString("userid", "");
		HttpUtils.doPostAsyn(Config.HOME_INIT + "&userid=" + userId, "",mHandler,
				Config.CODE_HOME_INIT);

//		 HttpUtils.doGetAsyn(Config.OUTMONEY_RECORD + "&type=0", mHandlers,
//		 Config.CODE_OUTMONEY_INIT);

//		checkdata();

	}

	private Handler mHandler = new Handler() {

		private int one;
		private int two;
		private int three;

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();

			switch (msg.what) {
				case Config.CODE_CHECKBACKMONEY:
					try {
						String reString = msg.obj.toString();
						JSONObject response = new JSONObject(reString);
						String code = response.getString("code");
						if(code.equals("1")){
							Intent intents = new Intent(ac, BackMoney2Activity.class);
							intents.putExtra("jkid", jkid);
							startActivity(intents);
						}else{
							new AlertDialog(ac).builder().setMsg(response.getString("msg"))
									.setNegativeButton("确定", new OnClickListener() {
										@Override
										public void onClick(View v) {


										}
									}).show();
						}
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						checkdata();
					}

					break;
			case Config.CODE_HOME_INIT:
//				Toast.makeText(ac, "url请求成功", Toast.LENGTH_SHORT).show();
				checkdata();
				try {
					// {"mobilephone":"17620110768","username":"GSD22","phone":"17620***68","creditlimit":"5000",
					// "isyhbd":"0","isshenfen":"0","islianxi":"0",
					// "err":0,"isjob":"0","rzstatus":"0","usablecreditlimit":"500","lastdate":"2017-02-22 17:39:09.0"}
					String reString = msg.obj.toString();
					JSONObject jsonObject = new JSONObject(reString);

					// "dataJK":{"id":8,"cl03_status":0,"yuq_ts":null,"cl_status":0,"sjds_money":420,"sjsh_money":600,"cl02_status":0,"jk_money":800}
					if (jsonObject.getString("dataJK") == "null") {
						out_money_txt.setText("借款");

					} else {
						JSONObject dataJK = jsonObject.getJSONObject("dataJK");
						if (dataJK.length() == 0) {
							out_money_txt.setText("借款");
						} else {
							jkid = dataJK.optString("id");
							int loan_status = dataJK.optInt("loan_status");
							int video_status = dataJK.optInt("video_status");
							int isrepay = dataJK.getInt("isrepay");//是否还款
							int over_days = dataJK.optInt("over_days");
							double over_moeny = dataJK.optDouble("over_moeny");
							double actual_amount = dataJK.optDouble("actual_amount");
							//0未审核，1一审成功、2一审失败、3二审成功、4二审失败、5三审成功、6三审失败、7放款成功、8放款失败
							switch (loan_status) {
								case 0:
                                case 1:
                                    out_money_txt.setText("查看借款详情");
                                    break;
								case 5:
									out_money_txt.setText("等待放款中");
									break;
								case 2:
								case 4:
								case 6:
								case 8:
									out_money_txt.setText("借款");
									break;
								case 3:
									if (video_status==1){
										out_money_txt.setText("查看借款详情");
									}else{
										out_money_txt.setText("上传视频");
									}
									break;
								case 7:
									if (isrepay == 0) {
										out_money_txt.setText("还款");
									} else if (isrepay == 1) {
										out_money_txt.setText("借款");
									}
									break;
							}
							if (loan_status >= 3&&loan_status<7) {
								get_money.setText("￥"+ actual_amount);
								txt.setText("审批金额");
							}if(loan_status==7){
								double money = 0.00;
								if (over_days==0){
									money = actual_amount;
								}else{
									money = actual_amount+over_moeny;
								}
								get_money.setText("￥"+ Formatdou.formatdou(money));
								txt.setText("还款金额");
							}else {
								get_money.setText("￥"
										+ jsonObject.getString("creditlimit"));
								txt.setText("借款额度");
							}

						}

					}

					sfzmrz=Integer.parseInt(jsonObject
							.getString("sfzmrz"));
					rzstatus = Integer.parseInt(jsonObject
							.getString("rzstatus"));
					isshenfen = Integer.parseInt(jsonObject
							.getString("isshenfen"));
					isjob = Integer.parseInt(jsonObject.getString("isjob"));
					islianxi = Integer.parseInt(jsonObject
							.getString("islianxi"));
					istaobao = Integer.parseInt(jsonObject
							.getString("istaobaoyz"));// istaobaoyz isjingdongyz
														// isyyshang
					isjd = Integer.parseInt(jsonObject
							.getString("isjingdongyz"));
					ismobile = Integer.parseInt(jsonObject
							.getString("isyyshang"));

					mobilephone = jsonObject.getString("mobilephone");
					cardBank = jsonObject.getString("rzcard");

					wdXiaoXi = jsonObject.getInt("wdXiaoXi");
					if (wdXiaoXi == 1) {
						news_warm.setVisibility(View.VISIBLE);
					} else {
						news_warm.setVisibility(View.INVISIBLE);
					}
					isApplerz =  jsonObject.getInt("isApplerz");
					int invest_status = Integer.parseInt(jsonObject
							.getString("invest_status"));
					SharedPreferences sp = ac.getSharedPreferences("config",
							ac.MODE_PRIVATE);
					Editor editor = sp.edit();
					editor.putInt("rzstatus", rzstatus);
					editor.putInt("invest_status", invest_status);
					editor.commit();

				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					checkdata();
				}
				
				break;
			case Config.CODE_URL_ERROR:
				Toast.makeText(ac, "url错误", Toast.LENGTH_SHORT).show();
				checkdata();
				break;
			case Config.CODE_NET_ERROR:
				Toast.makeText(ac, "网络错误", Toast.LENGTH_SHORT).show();
				checkdata();
				break;

			case Config.CODE_BANK:
				String result = msg.obj.toString();
				try {
					// {"mobilephone":"17620110768","username":"GSD22","phone":"17620***68","creditlimit":"5000",
					// "isyhbd":"0","isshenfen":"0","islianxi":"0",
					// "err":0,"isjob":"0","rzstatus":"0","usablecreditlimit":"500","lastdate":"2017-02-22 17:39:09.0"}
					JSONObject jsonObject = new JSONObject(result);

					rzstatus = Integer.parseInt(jsonObject
							.getString("rzstatus"));
					if (rzstatus==0) {
						setDialog("bank", "请先绑定银行卡！");
					}
					isshenfen = Integer.parseInt(jsonObject
							.getString("isshenfen"));
					isjob = Integer.parseInt(jsonObject.getString("isjob"));
					islianxi = Integer.parseInt(jsonObject
							.getString("islianxi"));
					istaobao = Integer.parseInt(jsonObject
							.getString("istaobaoyz"));// istaobaoyz isjingdongyz
														// isyyshang
					isjd = Integer.parseInt(jsonObject
							.getString("isjingdongyz"));
					ismobile = Integer.parseInt(jsonObject
							.getString("isyyshang"));

					mobilephone = jsonObject.getString("mobilephone");
					cardBank = jsonObject.getString("rzcard");
					wdXiaoXi = jsonObject.getInt("wdXiaoXi");
					if (wdXiaoXi == 1) {
						news_warm.setVisibility(View.VISIBLE);
					} else {
						news_warm.setVisibility(View.INVISIBLE);
					}

					int invest_status = Integer.parseInt(jsonObject
							.getString("invest_status"));
					SharedPreferences sp = ac.getSharedPreferences("config",
							ac.MODE_PRIVATE);
					Editor editor = sp.edit();
					editor.putInt("rzstatus", rzstatus);
					editor.putInt("invest_status", invest_status);
					editor.commit();
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				break;

			default:
				break;
			}
		};
	};

	private void checkdata() {
		// 启动子线程异步加载数据
		new Thread() {

			@Override
			public void run() {
				Message msg = Message.obtain();
				HttpURLConnection conn = null;
				try {
					// 本机地址用localhost, 但是如果用模拟器加载本机的地址时,可以用ip(10.0.2.2)来替换
					URL url = new URL(Config.OUTMONEY_RECORD + "&type=0");
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("POST");// 设置请求方法
					conn.setConnectTimeout(10000);// 设置连接超时
					conn.setReadTimeout(10000);// 设置响应超时, 连接上了,但服务器迟迟不给响应
					conn.connect();// 连接服务器

					int responseCode = conn.getResponseCode();// 获取响应码
					if (responseCode == 200) {
						InputStream inputStream = conn.getInputStream();
						String result = StreamUtils.readFromStream(inputStream);
						msg.obj = result;
						msg.what = Config.CODE_OUTMONEY_INIT;
					}
				} catch (MalformedURLException e) {
					// url错误的异常
					msg.what = Config.CODE_URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					// 网络错误异常
					msg.what = Config.CODE_NET_ERROR;
					e.printStackTrace();
				} finally {

					mHandlers.sendMessage(msg);
					if (conn != null) {
						conn.disconnect();// 关闭网络连接
					}
				}
			}
		}.start();
	}

	private Handler mHandlers = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case Config.CODE_URL_ERROR:
				Toast.makeText(ac, "url错误", Toast.LENGTH_SHORT).show();
				break;
			case Config.CODE_NET_ERROR:
				Toast.makeText(ac, "网络错误", Toast.LENGTH_SHORT).show();
				break;

			case Config.CODE_OUTMONEY_INIT:
				String result = msg.obj.toString();
				try {
					JSONArray jsonArray = new JSONArray(result);
					arrPojos = new ArrayList<PersonPojo>();
//					record_list.isStart = false;
					if(jsonArray.length()>0){
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject json = jsonArray.getJSONObject(i);
							PersonPojo pojo = new PersonPojo();
							String time[] = json.getString("create_date")//2017-04-21 14:31:10
									.split(" ");
							String time1[] = time[0].split("-");
							String time2[] = time[1].split(":");
							pojo.setCreate_date(time1[1] + "/" + time1[2]+" "+time2[0] + ":" + time2[1]);

							pojo.setCardusername(json.getString("cardusername")
									.substring(0, 1) + "**");
							pojo.setJk_money(json.getInt("jk_money"));
							arrPojos.add(pojo);
						}
//					if (time.cancel();){
						time.schedule(new TimeTaskScroll(ac, record_list, arrPojos), 20,
								20);
//					}
					}


				} catch (JSONException e) {
					Toast.makeText(ac, "数据解析错误", Toast.LENGTH_SHORT).show();
					System.out.println("数据解析错误" + e + msg.what);
					System.out.println("数据解析状态" + msg.what);
					e.printStackTrace();
				}

				break;

			default:
				break;
			}
		};
	};
	private TextView txt;
	private ImageView news_warm;
	private CatLoadingView dialog;
	private String userId;
	private Timer time;

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (time!=null) {
			time.cancel();
		}
		
		super.onDestroy();
	}
	
	
	
	private void setDialog(final String type, String msg) {
		new AlertDialog(ac).builder().setMsg(msg)
				.setNegativeButton("确定", new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (type == "camera") {
							startActivity(new Intent(ac, CameraActivity.class));
						}
						if (isApplerz ==0) {// 请绑定银行卡
							Intent intent = new Intent(ac,
									BindCard2Activity.class);
							startActivity(intent);
						}
						else if (isshenfen != 1) {// 请填写个人信息
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						} else if (isjob != 1) {// 请填写工作信息
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						} else if (islianxi != 1) {// 请填写联系人信息
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						} else if (ismobile != 1) {
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						} else if (isjd != 1 || istaobao != 1) {
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						}else if (sfzmrz!=1) {
							Intent intent = new Intent(ac, MyInfoActivity.class);
							startActivity(intent);
						}

					}
				}).show();
	}

}
